package com.nolydake.swingnote.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;

import com.hexidec.ekit.Ekit;
import com.nolydake.swingnote.gui.ext.ImagePanel;
import com.nolydake.swingnote.gui.ext.fordertree.ForderTree;
import com.nolydake.swingnote.gui.ext.listener.LinkListener;
import com.nolydake.swingnote.gui.list.ForderPanel;
import com.nolydake.swingnote.gui.list.NotePanel;
import com.nolydake.swingnote.gui.renderer.DataListCellRenderer;
import com.nolydake.swingnote.gui.renderer.MenuTreeCellRenderer;
import com.nolydake.swingnote.model.Note;
import com.nolydake.swingnote.model.NoteForder;
import com.nolydake.swingnote.service.note.INoteService;
import com.nolydake.swingnote.service.note.NoteServiceFactory;
import com.nolydake.swingnote.util.FileUtil;
import com.nolydake.swingnote.util.ImageUtil;

/**
 * 系统的主界面
 * 
 * @author NOLY DAKE
 *
 */
public class MainFrame extends JFrame {

    /**
     * 日志对象
     */
    private static final Logger LOG = Logger.getLogger(MainFrame.class);

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -4117500955440516455L;

    /**
     * 列表面板：列出左侧菜单选择文件夹下的所有目录以及日记
     */
    private JList<JPanel> dataList = null;

    /**
     * 列表面板数据模型
     */
    private DefaultListModel<JPanel> datalistModel = null;

    /**
     * 列表面板中的目录列表
     */
    private List<NoteForder> dataListForders = new ArrayList<NoteForder>();

    /**
     * 目录树
     */
    private ForderTree forderTree = null;

    /**
     * 目录树的节点对象
     */
    private DefaultMutableTreeNode forderTreeRootNode = null;

    JTextPane jviewPanel = null;

    private List<Note> notes = new ArrayList<Note>();

    public MainFrame() {
        super("测试");
        initGui();
    }

    private void dataListChange(NoteForder forder) {

        INoteService noteService = NoteServiceFactory.getService();
        List<NoteForder> tempNoteForders = noteService.loadForders(forder);
        List<Note> tempNotes = noteService.loadNotes(forder);

        notes.clear();
        notes.addAll(tempNotes);
        dataListForders.clear();
        dataListForders.addAll(tempNoteForders);

        flushDataList();

        if (forder.lastUpdateTime == null) {
            // 根节点
        } else {
        }

        dataList.setSelectedIndex(0);
    }

    /**
     * 选了一条:
     * 
     * @param e
     */
    private void dataListValueChanged(ListSelectionEvent e) {

        // 因为鼠标点击会存在两次的事件，所以我们只处理松开的事件
        if (e.getValueIsAdjusting()) {
            return;
        }

        int index = dataList.getSelectedIndex();

        // 如果选择的数据行小于0，不进行任何处理
        if (index < 0) {
            return;
        }

        // 使用目录，没有操作
        int forderSize = dataListForders.size();
        if (index < forderSize) {
            LOG.info("选择了文件夹，什么都不做");
            // 什么都不做
            return;
        }

        Note note = notes.get(index - forderSize);
        LOG.info("选择了文件" + note.name);

        String noteContent = FileUtil.read2String(new File(note.id), "UTF-8");
        jviewPanel.setText(noteContent);
    }

    private void flushDataList() {

        datalistModel.removeAllElements();
        for (NoteForder noteForder : dataListForders) {
            datalistModel.addElement(new ForderPanel(noteForder));
        }

        for (Note note : notes) {
            datalistModel.addElement(new NotePanel(note));
        }

        dataList.setModel(datalistModel);
    }

    /**
     * 目录树值的替换
     * 
     * @param e
     */
    private void forderTreeValueChanged(TreeSelectionEvent e) {

        TreePath newPath = e.getNewLeadSelectionPath();

        DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) newPath.getLastPathComponent();
        NoteForder forder = (NoteForder) node1.getUserObject();

        if (LOG.isDebugEnabled()) {
            LOG.debug("选择了节点:" + forder.id);
        }

        dataListChange(forder);
    }

    /**
     * 初始化中间的面板
     * 
     * @return
     * @throws IOException
     */
    private Component initCenterPanel() throws IOException {

        JSplitPane centerPanel = new JSplitPane();
        centerPanel.setDividerLocation(200);
        //////////////////////////////////////////////////
        // 记录区
        JSplitPane notesPanel = new JSplitPane();
        notesPanel.setDividerLocation(200);

        centerPanel.setLeftComponent(initMenuPanel());// 菜单面板菜单（一般情况下，放置在左侧）
        centerPanel.setRightComponent(notesPanel);

        //////////////////////////////////////////////////
        // 列表
        JScrollPane listPanel = new JScrollPane();
        listPanel.setMinimumSize(new Dimension(100, 100));

        datalistModel = new DefaultListModel<JPanel>();
        dataList = new JList<JPanel>(datalistModel);
        dataList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        dataList.setCellRenderer(new DataListCellRenderer());
        listPanel.setViewportView(dataList);
        dataList.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                dataListValueChanged(e);
            }

        });

        // 编辑区
        JPanel viewPanel = new JPanel();
        viewPanel.setLayout(new BorderLayout());

        JPanel viewTitlePanel = new JPanel();
        JScrollPane viewCenterPanel = new JScrollPane();
        JPanel btnsPanel = new JPanel();

        jviewPanel = new JTextPane();
        jviewPanel.setContentType("text/html");
        viewCenterPanel.setViewportView(jviewPanel);

        viewPanel.add(viewTitlePanel, BorderLayout.NORTH);
        viewPanel.add(viewCenterPanel, BorderLayout.CENTER);
        viewPanel.add(btnsPanel, BorderLayout.SOUTH);

        notesPanel.setLeftComponent(listPanel);
        notesPanel.setRightComponent(viewPanel);

        return centerPanel;
    }

    private void initGui() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 页面分为上下左中4个部分
        this.add(initToolBarPanel(), BorderLayout.NORTH);
        this.add(initSouthPanel(), BorderLayout.SOUTH);
        try {
            this.add(initCenterPanel(), BorderLayout.CENTER);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 设置树的展示效果
        forderTree.setSelectionPath(forderTree.getPathForRow(0));

        this.setSize(800, 600);
        this.setLocationRelativeTo(null);
    }

    /**
     * 菜单栏
     * 
     * @return
     */
    private Component initMenuPanel() {

        // 主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel northPanel = new JPanel();
        JScrollPane centerPanel = new JScrollPane();
        ImagePanel southPanel = new ImagePanel();

        mainPanel.add(northPanel, BorderLayout.NORTH);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(southPanel, BorderLayout.SOUTH);

        // 下面再细细的每个界面初始化
        // SOUTH：这里是一个广告区
        southPanel.setImage(ImageUtil.loadImageIcon("common", "ad.jpg").getImage());
        southPanel.setPreferredSize(new Dimension(192, 90));
        southPanel.addMouseListener(new LinkListener(southPanel, "http://git.oschina.net/spbun/SwingNote"));

        // NORTH
        northPanel.setBackground(Color.LIGHT_GRAY);
        JLabel label = new JLabel("NOLY DAKE");
        northPanel.add(label);

        // CENTER
        forderTreeRootNode = new DefaultMutableTreeNode();

        // 获取service对象
        INoteService noteService = NoteServiceFactory.getService();
        noteService.fillForderTreeRootNode(forderTreeRootNode);

        forderTree = new ForderTree(forderTreeRootNode);
        forderTree.setRootVisible(false);
        forderTree.setCellRenderer(new MenuTreeCellRenderer());

        centerPanel.setViewportView(forderTree);
        forderTree.addTreeSelectionListener(new TreeSelectionListener() {

            public void valueChanged(TreeSelectionEvent e) {
                forderTreeValueChanged(e);
            }
        });

        mainPanel.setBorder(BorderFactory.createEtchedBorder());
        return mainPanel;
    }

    private Component initToolBarPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEADING));

        JButton btnAddForder = new JButton();
        btnAddForder.setText("新建文件夹");
        btnAddForder.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                forderTree.addForder();
            }
        });
        panel.add(btnAddForder);

        JButton btnAddNotes = new JButton();
        btnAddNotes.setText("新建笔记");
        btnAddNotes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                Ekit.main(new String[] {});

                // new NoteEditDialog(MainFrame.this).setVisible(true);
            }
        });
        panel.add(btnAddNotes);

        panel.setBorder(BorderFactory.createEtchedBorder());
        return panel;
    }

    private Component initSouthPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.RIGHT));

        JLabel label = new JLabel("总计4408");
        panel.add(label);

        panel.setBorder(BorderFactory.createEtchedBorder());
        return panel;
    }
}
